#include "stm32f10x.h"
#include "stm32f10x_gpio.h"

typedef enum
{
	KeyScanState_0 = 0x00,
	KeyScanState_1 = 0x01,
	KeyScanState_2 = 0x02,
}KeyScanState_Typedef;
#define KEY0PIN GPIO_Pin_4
#define KEY1PIN GPIO_Pin_3
#define LED0PIN GPIO_Pin_5
#define LED1PIN GPIO_Pin_5
#define KEYPORT GPIOE
#define LED0PORT GPIOB
#define LED1PORT GPIOE
vu32 flag=0;
void RccInitialisation(void);
void GpioInitialisation(void);
void SystickInitialisation(void);
int main(void)
{
	vu16 KeyPortStatus = 0;
	KeyScanState_Typedef KeyScanState = KeyScanState_0;
	RccInitialisation();
	GpioInitialisation();
	SystickInitialisation();
	while(1)
	{
		if(flag==1)
		{
			flag = 0;
			KeyPortStatus = GPIO_ReadInputData(KEYPORT) & 0x0018;
			switch(KeyScanState)
			{
				case KeyScanState_0:
				{
					if(KeyPortStatus != 0x0018)
					{
						KeyScanState = KeyScanState_1;
					}
					break;
				}
				case KeyScanState_1:
					if(KeyPortStatus != 0x0018)
					{
						if(GPIO_ReadInputDataBit(KEYPORT,KEY0PIN))
						{
							GPIO_WriteBit(LED0PORT,
							LED0PIN,
							(BitAction)(1-GPIO_ReadOutputDataBit
							(LED0PORT,LED0PIN)));
						}
						if(GPIO_ReadInputDataBit(KEYPORT,KEY1PIN))
						{
							GPIO_WriteBit(LED1PORT,
							LED1PIN,
							(BitAction)(1-GPIO_ReadOutputDataBit
							(LED1PORT,LED1PIN)));
						}
						KeyScanState=KeyScanState_2;
					}
					else
					{
						KeyScanState=KeyScanState_0;
					}
					break;
				case KeyScanState_2:
					if(KeyPortStatus==0x0018)
					{
						KeyScanState = KeyScanState_0;
					}
					break;
			}
		}
	}
}
void RccInitialisation(void)
{
	ErrorStatus HSEStartUpStatus;
	RCC_DeInit();
	RCC_HSEConfig(RCC_HSE_ON);
	HSEStartUpStatus = RCC_WaitForHSEStartUp();
	if(HSEStartUpStatus == SUCCESS)
	{
		RCC_HCLKConfig(RCC_SYSCLK_Div1);
		RCC_PCLK2Config(RCC_HCLK_Div1);
		RCC_PCLK2Config(RCC_HCLK_Div2);
		FLASH_SetLatency(FLASH_Latency_2);
		FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable);
		RCC_PLLConfig(RCC_PLLSource_HSE_Div1,RCC_PLLMul_9);
		RCC_PLLCmd(ENABLE);
		while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET);
		RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
		while(RCC_GetSYSCLKSource() != 0x08);
	}
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE,ENABLE);
}
void GpioInitialisation(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Pin = KEY0PIN|KEY1PIN;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_Init(KEYPORT,&GPIO_InitStructure);
	GPIO_InitStructure.GPIO_Pin = LED0PIN;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode =  GPIO_Mode_Out_PP;
	GPIO_Init(LED0PORT,&GPIO_InitStructure);
	GPIO_InitStructure.GPIO_Pin = LED1PIN;
	GPIO_Init(LED1PORT,&GPIO_InitStructure);
}

void SystickInitialisation(void)
{
	SysTick_Config(72000000/50);
}
